package com.nxn.dinner.web.action.order;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.nxn.core.utils.GenerateRandomUtils;
import com.nxn.core.web.action.base.CRUDAction;
import com.nxn.dinner.model.DeliveryOrder;
import com.nxn.dinner.model.OrderList;
import com.nxn.dinner.model.DeliveryOrder.OrderStatus;
import com.nxn.dinner.service.DeliveryOrderService;

@Controller("deliveryOrderAction")
@Scope("prototype")
 
public class DeliveryOrderAction extends CRUDAction<DeliveryOrder, Long> {
	private static final long serialVersionUID = -6178118253502338260L;
	
	private int searchType;
	private String key;
//	private List<OrderList> orderList;
	
	@Autowired
	private DeliveryOrderService deliveryOrderService ;
	
	/**
	 * 在list()前执行二次绑定.
	 */
	public void prepareList() throws Exception {
		//可以考虑更好的实现方式（用于传递查询参数）
		entity = new DeliveryOrder();
	}
	
	@Override
	protected String buildHQL() {
		StringBuilder hqlBuiler = new StringBuilder();
		hqlBuiler.append(super.buildHQL());
		
		DeliveryOrder order = getModel();
		if(StringUtils.isNotEmpty(order.getOrderNo().trim())) {
			hqlBuiler.append(" where orderNo = :orderNo");
		} else {
			hqlBuiler.append(" where contactName = :contactName");
		}
		
		return hqlBuiler.toString();
	}

	@Override
	protected Map<String, Object> buildQueryMap() {
		Map<String, Object> queryMap = new HashMap<String, Object>();
		
		DeliveryOrder order = getModel();
		if(StringUtils.isNotEmpty(order.getOrderNo().trim())) {
			queryMap.put("orderNo", order.getOrderNo());
		} else {
			queryMap.put("contactName", order.getContactName());
		}
		
		return queryMap;
	}
	
	@Action(
		results={@Result(name="order-success", location="/WEB-INF/content/order/order-success.jsp")}
	)
	public String save() throws Exception {
		DeliveryOrder order = getModel();
		order.setOrderNo(GenerateRandomUtils.generateOrderNo());
		
		// X-Michael cascade save
		for(OrderList orderList : order.getOrderList()) {
			orderList.setDeliveryOrder(order);
		}
		
		order.getOrderSet().addAll(order.getOrderList());
		order.setCreateTime(new Date());
		order.setStatus(OrderStatus.PROCESSING.getStatus());
		
		super.save();
		
		return "order-success";
	}

	@Override
	protected boolean isAutoCount() {
		return false;
	}

}
